package com.example.experiment8;


import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;

import android.database.ContentObserver;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;

import android.view.SurfaceHolder;
import android.view.SurfaceView;

import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;

import android.widget.SeekBar;


import com.alibaba.android.arouter.facade.annotation.Route;

import java.io.IOException;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = "/experiment8/PlayVideo")
public class PlayVideo extends AppCompatActivity {

    String path;
    MediaPlayer mediaPlayer;
    Timer timer;
    TimerTask timerTask;
    AudioManager audioManager;
    SharedPreferences sharedPreferences;
    @BindView(R.id.surfaceView)
    SurfaceView surfaceView;
    @BindView(R.id.pause_start)
    ImageButton imageButtonPauseStart;
    @BindView(R.id.videoSeekBar)
    SeekBar videoSeekBar;
    @BindView(R.id.buttomControl)
    ConstraintLayout buttomControl;
    @BindView(R.id.volumeSeekBar)
    SeekBar volumeSeekBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE); //去除标题栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorBlack,null));
        setContentView(R.layout.activity_play_video);
        ButterKnife.bind(this);
        path=getIntent().getStringExtra("path");
        mediaPlayer=new MediaPlayer();
        audioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
        surfaceView.getHolder().setKeepScreenOn(true);
        surfaceView.getHolder().addCallback(new SurfaceListener());
        setVolumeSeekBar();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                imageButtonPauseStart.setImageDrawable(getDrawable(R.drawable.play));
            }
        });
    }
    @OnClick(R.id.pause_start)
    void cliPause(){
        if(mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            imageButtonPauseStart.setImageDrawable(getDrawable(R.drawable.play));
        }
        else{
            mediaPlayer.start();
            imageButtonPauseStart.setImageDrawable(getDrawable(R.drawable.pause));
        }
    }
    @OnClick(R.id.btn_left)
    void cliLeft(){
        mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-5000);
    }
    @OnClick(R.id.btn_right)
    void cliRight(){
        mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+5000);
    }
    @OnClick(R.id.main)
    void cliMain(){
        if(buttomControl.getVisibility()==ConstraintLayout.INVISIBLE){
            buttomControl.setVisibility(ConstraintLayout.VISIBLE);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            buttomControl.setVisibility(ConstraintLayout.INVISIBLE);
        }
    }
    @OnClick(R.id.btn_stop)
    void cliStop(){
        if(mediaPlayer.isPlaying()){
            imageButtonPauseStart.setImageDrawable(getDrawable(R.drawable.play));
            mediaPlayer.pause();
        }
        mediaPlayer.seekTo(0);
    }
    private void setVolumeSeekBar(){
        volumeSeekBar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        volumeSeekBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
        volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        onVolumeChange();
    }
    private void onVolumeChange(){
        Handler handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what==1){
                    volumeSeekBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
                }
                return false;
            }
        });

        MyContentObserver myContentObserver=new MyContentObserver(handler,this);
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, myContentObserver);

    }
    private void play() throws IOException {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(path);
        mediaPlayer.setDisplay(surfaceView.getHolder());
        mediaPlayer.prepare();
        setVideoOrientation();
        mediaPlayer.start();
    }
    private void setVideoOrientation(){
        Configuration configuration=this.getResources().getConfiguration();
        WindowManager windowManager=getWindowManager();
        DisplayMetrics displayMetrics=new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        ConstraintLayout.LayoutParams params=(ConstraintLayout.LayoutParams)surfaceView.getLayoutParams();
        if(configuration.orientation==Configuration.ORIENTATION_PORTRAIT){
            params.height=mediaPlayer.getVideoHeight()*displayMetrics.widthPixels/mediaPlayer.getVideoWidth();
            params.width=displayMetrics.widthPixels;
            surfaceView.setLayoutParams(params);
        }
        else{
            params.height=displayMetrics.heightPixels;
            params.width=mediaPlayer.getVideoWidth()*displayMetrics.heightPixels/mediaPlayer.getVideoHeight();
            surfaceView.setLayoutParams(params);
        }
    }

    private void setVideoSeekBar(){
        Handler handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what==1){
                    videoSeekBar.setMax(mediaPlayer.getDuration());
                    videoSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                    SharedPreferences.Editor editor=sharedPreferences.edit();
                    editor.putInt("index",mediaPlayer.getCurrentPosition());
                    editor.commit();
                }
                return false;
            }
        });
        timer=new Timer();
        timerTask=new TimerTask() {
            @Override
            public void run() {
                Message message=new Message();
                if(mediaPlayer.getDuration()>0)
                    message.what=1;
                else
                    message.what=0;
                handler.sendMessage(message);
            }
        };
        timer.schedule(timerTask,0,80);
        videoSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            boolean touched=false;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(touched==true)
                    mediaPlayer.seekTo(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                touched=true;
                mediaPlayer.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                touched=false;
                mediaPlayer.start();
            }
        });
    }
    private class SurfaceListener implements SurfaceHolder.Callback{

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                play();
            }catch (Exception e){
                e.printStackTrace();
            }
            setVideoSeekBar();
            setVolumeSeekBar();
            sharedPreferences=getSharedPreferences("videoProgress",MODE_PRIVATE);
            mediaPlayer.seekTo(sharedPreferences.getInt("index",0));
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            timer.cancel();
            timer=null;
            timerTask.cancel();
            timerTask=null;
            mediaPlayer.reset();
        }
    }
    public class MyContentObserver extends ContentObserver{
        Context context;
        Handler handler;
        public MyContentObserver(Handler handler,Context context) {
            super(handler);
            this.context=context;
            this.handler=handler;
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            Message message=new Message();
            message.what=1;
            handler.sendMessage(message);
        }
    }

}
